<!-- 首页html列表 -->
<template>
  <div class="DealerInfoStyle">
    <div class="cardAdmin">
      <div class="formContainer">
        <div class="formSearch">
          <span
            style="padding: 0 10px; text-align: right; line-height: 40px; font-weight: 700; font-size: 15px;">名称：</span>
          <el-input style="flex: 3;" v-model="form.admin_name"></el-input>
        </div>
        <div style="position: absolute;left: 10px;bottom: 5px;">
          <el-button type="success" icon="el-icon-circle-plus-outline" size="small" @click="addbtn()">新增首页html</el-button>
        </div>
      </div>
    </div>

    <!-- 表格 -->
    <el-table :data="CompanyTable" border style="width: 100%;min-height: 78%;max-height: 78%;overflow: auto;">
      <el-table-column resizable prop="id" label="id" width="60" align="center">
      </el-table-column>

      <el-table-column resizable prop="imgdata[0]" label="图片1" width="auto" min-width="180px" align="center">
        <template slot-scope="scope">
          <el-image style="width: 50px;height:20px" :src="'' + scope.row.imgdata[0]" :fit="roleHeadgear"
            :preview-src-list="['' + scope.row.imgdata[0]]">
            <div slot="error" class="image-slot" style="width: 50px;">
              <div style="width: 50px;">{{ scope.row.imgdata[0] == '' ? '加载失败' : '空图片或者地址错误' }}</div>
            </div>
          </el-image>
        </template>
      </el-table-column>

      <el-table-column resizable prop="imgdata[1]" label="图片2" width="auto" min-width="180px" align="center">
        <template slot-scope="scope">
          <el-image style="width: 50px;height:20px" :src="'' + scope.row.imgdata[1]" :fit="roleHeadgear"
            :preview-src-list="['' + scope.row.imgdata[1]]">
            <div slot="error" class="image-slot" style="width: 50px;">
              <div style="width: 50px;">{{ scope.row.imgdata[1] == '' ? '加载失败' : '空图片或者地址错误' }}</div>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column resizable prop="type" label="类型" width="auto" min-width="120px" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.type == 1">图片</div>
          <div v-if="scope.row.type == 2">文字</div>
          <div v-if="scope.row.type == 3">图文</div>
          <div v-if="scope.row.type == 4">视频</div>
        </template>
      </el-table-column>
      <el-table-column resizable prop="sort" label="版序" width="auto" min-width="100px" align="center">
      </el-table-column>
      <el-table-column resizable prop="name" label="名字" width="auto" min-width="200px" align="center">
      </el-table-column>
      <el-table-column resizable prop="add_time" label="添加时间" width="auto" min-width="250px" align="center">
      </el-table-column>




      <el-table-column resizable label="操作" width="150"  align="center">
        <template slot-scope="scope">
          <el-button @click="tableEditing(scope.row)" type="primary" plain size="small">编辑</el-button>
          <el-button @click="del_homepageSystemHtmlDeletion(scope.row.id)" type="danger" plain size="small">刪除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="text-align: right; margin-top: 5px;">
      <el-pagination background layout="prev, pager, next,total" :total="total" :page-size="pagesize"
        @current-change="current_change"></el-pagination>
    </div>

    <!-- 弹窗 -->
    <el-dialog  :close-on-click-modal="false" :title="titles" :visible.sync="dialogVisible" width="90%" @close="handleClose" top="5vh">

      <div class="pop-up-form">
        <div style="display: flex;justify-content: center;width: 95%;margin: 8px 0;">
          <div style="flex: 1;">
            <span style="flex: 4; text-align: right; line-height: 40px; font-weight: 700; font-size: 15px;">类型：</span>
            <el-select style="flex: 6;" v-model="addform.type" placeholder="类型" disabled>
              <el-option v-for="item in typesdata" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <span
              style="flex: 4; text-align: right; line-height: 40px; font-weight: 700; font-size: 15px;margin-left: 20px;">版序：</span>
            <el-select style="flex: 6;" v-model="addform.sort" placeholder="版序">
              <el-option label="1" value="1">
              </el-option>
              <el-option label="2" value="2">
              </el-option>
              <el-option label="3" value="3">
              </el-option>
              <el-option label="4" value="4">
              </el-option>
              <el-option label="5" value="5">
              </el-option>
            </el-select>
          </div>

        </div>
        <div style="width: 100%;display: flex;justify-content: space-around;background-color: #4dacd1;height: 500px;">
          <div style="display: flex;flex-direction: column;align-items: center;justify-content: center;">
            <ul>
              <li style="padding: 10px 0;color: #fff;max-width: 300px;font-size: 16px;">Powered by AI and senior
                investment professionals.
              </li>
              <li style="padding: 10px 0;color: #fff;max-width: 300px;font-size: 16px;">Using sophisticated valuation
                methods.
              </li>
              <li style="padding: 10px 0;color: #fff;max-width: 300px;font-size: 16px;">Focusing on economic cycle and
                market timing.
              </li>
              <li style="padding: 10px 0;color: #fff;max-width: 300px;font-size: 16px;">High return potential.
              </li>
              <li style="padding: 10px 0;color: #fff;max-width: 300px;font-size: 16px;">Extrodinary in risk management.
              </li>
            </ul>
          </div>
          <div style="display: flex;">
            <div
              style="height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center;">
              <!-- 触发上传的img1 -->
              <img style="width: 300px; height: 300px; border: 1px #f1f1f1 solid;" class="img1" :src="img1Src"
                alt="点击上传图片" @click="triggerFileInput('fileInput1')" />
              <!-- 隐藏的文件上传输入框1 -->
              <input style="display: none;" type="file" ref="fileInput1" id="roleHeadgear1" accept="image/*"
                @change="handleFileChange1" required />
            </div>
            <div
              style="height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; margin-left: 15px;">
              <!-- 触发上传的img2 -->
              <img style="width: 300px; height: 300px; border: 1px #f1f1f1 solid;" class="img2" :src="img2Src"
                alt="点击上传图片" @click="triggerFileInput('fileInput2')" />
              <!-- 隐藏的文件上传输入框2 -->
              <input style="display: none;" type="file" ref="fileInput2" id="roleHeadgear2" accept="image/*"
                @change="handleFileChange2" required />
            </div>
          </div>
          <div style="display: flex;flex-direction: column;align-items: center;justify-content: center;">
            <button
              style="width: 200px;height: 120px;padding: 9px;font-size: 16px;background-color: #75bd42;border-radius: 15px;border: none;">Sign
              up now and get 14-day trial for <span
                style="display: block;margin-top: 10px;font-size: 22px;font-weight: 700;">FREE!</span></button>
          </div>
        </div>

        <div class="pop-up-form" style="min-height: calc(100vh - 200px - 5vh - 54px - 120px - 40px);display: none;">
          <div style="width: 100%;padding: 0 0 0 4%;">
            <h3 style="flex: 2; text-align: center; line-height: 40px; font-weight: 700; font-size: 15px;width: 100%;">内容：
            </h3>
            <div style="border: 1px solid #ccc;height:auto">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
                :mode="mode" />
              <Editor style="height: calc(100vh - 200px - 5vh - 54px - 120px - 40px); overflow-y: hidden;" v-model="html"
                :defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated" @onChange="onChange"
                @onDestroyed="onDestroyed" @onMaxLength="onMaxLength" @onFocus="onFocus" @onBlur="onBlur"
                @customAlert="customAlert" @customPaste="customPaste" />
            </div>
          </div>
        </div>
      </div>


      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button v-show="titles == '新增'" type="primary" @click="add_homeSystemHtmlAdded()" size="small">确
          定</el-button>
        <el-button v-show="titles == '编辑'" type="primary" @click="upd_homeSystemHtmlEditing()" size="small">更
          新</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { homepageSystemHtmlList, homeSystemHtmlAdded, homeSystemHtmlEditing, homepageSystemHtmlDeletion, singleColumnContent, uploadImage } from "@/utils/api";
export default {
  name: 'CompanyInfo',
  components: { Editor, Toolbar },
  data() {
    return {
      imageLink: 'https://www.google.com/',
      // 富文本
      editor: null, // 富文本实例对象
      html: '', // 富文本初始html
      toolbarConfig: {
        excludeKeys: [
          // 'group-image',
          'group-video'
        ],
      },
      isVisible: false,
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          // 配置图片上传
          uploadImage: {
            server: '/admin/System/imgUpload', // 上传图片的地址
            fieldName: 'image', // 后端接收图片的字段名
            maxFileSize: 2 * 1024 * 1024, // 图片大小限制，单位 byte
            maxNumberOfFiles: 5, // 最多可上传图片数
            headers: {
              'token': localStorage.getItem('token'), // 将 token 添加在请求头中
            },
            allowedFileTypes: ['image/*'], // 限制文件类型
            onSuccess(file, res) {
              // 自定义处理上传成功后的逻辑
              console.log('图片上传成功', res, file)
              alert(res.msg)
            },
            onFailed(file, res) {
              console.log(res, file, '失败');
              // 自定义处理上传失败后的逻辑
              // console.error('图片上传失败', res);
            },
            // 自定义上传逻辑
            customInsert: (res, insertFn) => {
              const imageUrl = '' + res.data[0];

              insertFn(imageUrl);
            },
          }
        },

      },// 富文本提示
      mode: 'default', // or 'simple'
      form: {
        admin_name: ''
      },
      type: "", // 当前选择的语言
      addform: {
        type: 1,
        sort: 1,
        content: ''

      },
      CompanyTable: [],
      typesdata: [
        { value: 1, label: "图片" },
        { value: 2, label: "文字" },
        { value: 3, label: "图文" },
        { value: 4, label: "视频" }
      ],
      dialogVisible: false,
      total: 100, //总条数
      pagesize: 10, //指定展示多少条
      currentPage: 1, //当前页码
      titles: '',
      roleHeadgear: null,
      dangeColumn: [],
      row: {},
      roleHeadgear1: '',
      roleHeadgear2: '',
      img1y: require('@/assets/zzx1.jpg'), // img1的预览图片
      img2y: require('@/assets/zzx1.jpg'), // img2的预览图片
      img1Src: require('@/assets/zzx1.jpg'), // img1的预览图片
      img2Src: require('@/assets/zzx1.jpg'), // img2的预览图片

    };
  },
  mounted() {
    this.get_homepageSystemHtmlList()
  },

  methods: {
    triggerFileInput(refName) {
      this.$refs[refName].click(); // 触发文件上传输入框
    },
    // 处理第一个图片上传
    async handleFileChange1(event) {
      const file = event.target.files[0];
      if (file) {
        const formData = new FormData();
        formData.append('image', file);  // 添加文件
        formData.append('position', 'index'); // 添加position字段

        try {
          const response = await uploadImage(formData); // 调用上传接口
          console.log(response, '------------------------------------');
          this.img1Src = '' + response.data.data[0]; // 更新img1的预览地址
          this.roleHeadgear1 = response.data.data[0]
          this.$message.info(response.data.msg)
        } catch (error) {
          console.error('上传图片失败', error);
        }
      }
    },
    // 处理第二个图片上传
    async handleFileChange2(event) {
      const file = event.target.files[0];
      if (file) {
        const formData = new FormData();
        formData.append('image', file);  // 添加文件
        formData.append('position', 'index'); // 添加position字段

        try {
          const response = await uploadImage(formData); // 调用上传接口
          this.img2Src = '' + response.data.data[0]; // 更新img2的预览地址
          this.roleHeadgear2 = response.data.data[0]
          this.$message.info(response.data.msg)
        } catch (error) {
          console.error('上传图片失败', error);
        }
      }
    },
    // 查询首页html列表
    async get_homepageSystemHtmlList() {
      let data = JSON.parse(JSON.stringify(this.form));
      data.page = this.currentPage

      // 删除值为 "" 或 null 的字段
      Object.entries(data).forEach(([key, value]) => {
        if (value === "" || value === null) {
          delete data[key];
        }
      });

      const res = await homepageSystemHtmlList(data).catch((err) => {
        return console.error(err);
      });
      if (res && res.status == "200") {
        this.$message.success(res.data.message);
        this.CompanyTable = res.data.data
        for (let i = 0; i < this.CompanyTable.length; i++) {
          this.CompanyTable[i].imgdata = this.CompanyTable[i].content.split(',');

        }
        this.total = res.data.data.total
      } else {
        this.$message.error(res.data.message);
      }
    },
    // 新增首页html
    async add_homeSystemHtmlAdded() {
      let data = {}
      data.type = this.addform.type
      data.sort = this.addform.sort

      let imgurl = ''
      if (this.roleHeadgear1 !== '') {
        imgurl = this.roleHeadgear1
      }
      if (this.roleHeadgear2 !== '') {
        imgurl = imgurl + ',' + this.roleHeadgear2
      }
      if (imgurl !== '') {
        data.content = imgurl
      }
      const res = await homeSystemHtmlAdded(data).catch((err) => {
        this.$message.error(err.response.data.message)
        return console.error(err);
      });
      if (res && res.status == "200") {
        this.$message.success(res.data.message);
        this.get_homepageSystemHtmlList()
        this.roleHeadgear1 = ''
        this.roleHeadgear2 = ''
        this.dialogVisible = false
      } else {
        this.$message.error(res.data.message);
      }
    },
    // 查询单个首页html
    async get_singleColumnContent(id) {
      let data = {}
      const res = await singleColumnContent(data, id).catch((err) => {
        return console.error(err);
      });
      if (res && res.status == "200") {
        this.$message.success(res.data.message);

        this.dangeColumn = res.data.data.data
      } else {
        this.$message.error(res.data.message);
      }

    },
    // 更新首页html
    async upd_homeSystemHtmlEditing() {
      let data = {}
      data.id = this.addform.id
      data.sort = this.addform.sort

      let imgurl = ''
      if (this.roleHeadgear1 !== '') {
        imgurl = this.roleHeadgear1
      }
      if (this.roleHeadgear2 !== '') {
        imgurl = imgurl + ',' + this.roleHeadgear2
      }
      if (imgurl !== '') {
        data.content = imgurl
      }
      const res = await homeSystemHtmlEditing(data, this.addform.id).catch((err) => {
        return console.error(err);
      });
      if (res && res.status == "200") {
        this.$message.success(res.data.message);
        this.dialogVisible = false
        this.get_homepageSystemHtmlList()
        this.roleHeadgear1 = ''
        this.roleHeadgear2 = ''
      } else {
        this.$message.error(res.data.message);
      }
    },
    // 刪除首页html
    async del_homepageSystemHtmlDeletion(id) {
      try {
        await this.$confirm("是否继续执行操作？", "提示", {
          confirmButtonText: "是",
          cancelButtonText: "否",
          type: "warning",
        });

        // let data = { id };
        const res = await homepageSystemHtmlDeletion(id).catch((err) => {
          return console.error(err);
        });

        if (res && res.status == "200") {
          this.$message.success(res.data.message);
          this.dialogVisible = false;
          this.get_homepageSystemHtmlList();
        } else {
          this.$message.error(res.data.message);
        }
      } catch (error) {
        // 用户点击取消或关闭对话框
        console.error(error);
      }
    },
    // 关闭弹窗时
    handleClose() {
      this.addform = {
        type: 1,
        sort: 1,
        content: ''
      }
      this.html = ''
      this.isVisible = true
      this.$refs.fileInput1.value = null;
      this.$refs.fileInput2.value = null;

      this.roleHeadgear1 = ''
      this.roleHeadgear2 = ''
      this.img1Src = this.img1y
      this.img2Src = this.img2y
    },
    handleClosetable() {

    },
    // 分页
    current_change(currentPage) {
      this.currentPage = currentPage;
      this.get_homepageSystemHtmlList();
    },
    // 重置
    resetForm() {
      this.form = {
        admin_name: ''
      }
      this.currentPage = 1
      this.get_homepageSystemHtmlList();
    },
    // 编辑打开时
    tableEditing(row) {
      this.isVisible = false
      this.titles = '编辑'
      this.row = row
      this.dialogVisible = true
      const isTrue = (value) => {
        if (value == null || value == undefined || value === "null" || value === "undefined") {
          return false;
        }
        return true;
      };

      if (isTrue(row.imgdata[0])) {
        this.roleHeadgear1 = row.imgdata[0]
      }
      if (isTrue(row.imgdata[1])) {
        this.roleHeadgear2 = row.imgdata[1]
      }
      if (isTrue(row.imgdata[0])) {
        this.img1Src = '' + row.imgdata[0]
      }
      if (isTrue(row.imgdata[1])) {
        this.img2Src = '' + row.imgdata[1]
      }
      this.addform.id = row.id
    },
    // 新增打开时
    addbtn() {
      this.dialogVisible = true;
      this.titles = '新增'
      this.isVisible = true
    },
    // 富文本
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    // 组件销毁时销毁编辑器
    beforeDestroy() {
      const editor = this.editor
      if (editor == null) return
      editor.destroy()
    },
    onChange(editor) {
      console.log(editor, this.editor, '121212121')
    },
    onDestroyed(editor) { console.log('onDestroyed', editor) },
    onMaxLength(editor) { console.log('onMaxLength', editor) },
    onFocus(editor) { console.log('onFocus', editor) },
    onBlur(editor) { console.log('onBlur', editor) },
    customAlert(info, type) { window.alert(`customAlert in Vue demo\n${type}:\n${info}`) },
    customPaste(editor, event, callback) {
      console.log('ClipboardEvent 粘贴事件对象', event)
      // const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
      // const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
      // const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）

      // 自定义插入内容
      // editor.insertText('xxx')

      // 返回 false ，阻止默认粘贴行为
      // event.preventDefault()
      // callback(false) // 返回值（注意，vue 事件的返回值，不能用 return）

      // 返回 true ，继续默认的粘贴行为
      // callback(true)
      console.log(editor, event, callback);
    },
  },
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style>
.cell {
  font-size: 12px;
  white-space: nowrap !important;
}

.el-dialog__body {
  padding: 0 10px !important;
}

.demo-table-expand {
  font-size: 0;
  margin-left: 10px;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
<style lang="less" scoped>
.DealerInfoStyle {
  width: 100%;
  padding: 0 10px;
  // background-color: aquamarine;
  height: calc(100vh - 100px);
  // border: 1px #000 solid;

  .cardAdmin {
    position: relative;
    // height: 18%;
    width: 100%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    margin: 0;

    border: #ebeef5 solid 1px;
    padding: 0 5px;
    margin-bottom: 2px;


    .formContainer {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      padding: 0;
      align-self: baseline;
      padding-bottom: 40px;
    }

    .formSearch {
      width: 25%;
      min-width: 25%;
      margin: 10px 0;
      height: 40px;
      display: flex;
      justify-content: center;
    }
  }

  .pop-up-form {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    padding: 0;
    align-self: baseline;
    margin: 10px 0;
    justify-content: center;
    padding-right: 15px;

    .form-options {
      width: 100%;
      min-width: 100%;
      height: 40px;
      display: flex;
      justify-content: center;
      margin: 10px 0;
    }
  }
}
</style>
